package com.imti.xmlparserdemo;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class PullParseUtil
{

    public static List<StudentModel> parseStudentList(InputStream is)
        throws XmlPullParserException, IOException
    {
        List<StudentModel> dataList = null;

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = factory.newPullParser();

        parser.setInput(is, "utf-8");

        int eventType = parser.getEventType();

        StudentModel model = null;

        while (eventType != XmlPullParser.END_DOCUMENT)
        {
            switch (eventType)
            {
                case XmlPullParser.START_DOCUMENT:
                    dataList = new ArrayList<>();
                    break;

                case XmlPullParser.START_TAG:
                    String tagName = parser.getName();
                    switch (tagName)
                    {
                        case "student":
                            model = new StudentModel();
                            //按顺序获取标签属性值
                            model.setId(parser.getAttributeValue(0));
                            //按照命名控件获取属性值
//                            model.setId(parser.getAttributeValue(
//                                "http://schemas.android.com/apk/res/android","id"));
                            break;
                        case "name":
                            //获取标签中的value值<name>堂堂</name>
                            model.setName(parser.nextText());
                            break;

                        case "age":
                            model.setAge(parser.nextText());
                            break;
                    }
                    break;

                case XmlPullParser.END_TAG:
                    if (parser.getName().equals("student"))
                    {
                        dataList.add(model);
                    }
                    break;
            }

            eventType = parser.next();
        }

        return dataList;
    }
}
